package ipmsg.network;

import java.io.UnsupportedEncodingException;
import java.net.DatagramSocket;
import java.net.SocketException;

import com.czh.www.HexDataUtils;

import ipmsg.IpmsgConstants;
import ipmsg.etc.Command;
import ipmsg.etc.FileLinkList;
import ipmsg.etc.GlobalConstant;
import ipmsg.etc.GlobalVar;
import ipmsg.gui.GetRecFiles;
import ipmsg.gui.UtilityGui;

public class MsgDaemonProcessor extends Thread {
	private RefreshUsers fresh;

	public MsgDaemonProcessor(RefreshUsers fresh) {
		this.fresh = fresh;
		try {
			UtilityNet.msgSocket = new DatagramSocket(IpmsgConstants.DEFAULT_PORT);
		} catch (SocketException ex) {
		}
	}

	public void run() {
		try {
			for (;;) {
				GlobalVar.COMMAND_QUEUE_fULL.acquire();
				Command com = GlobalVar.popCommand();
				GlobalVar.COMMAND_QUEUE_EMPTY.release();

				com.show();

				int mood = GlobalConstant.GET_MODE(com.getFlag());
				int OPT = GlobalConstant.GET_OPT(com.getFlag());

				if ((OPT & 0x100) != 0) {
					Command tmpCom = new Command(GlobalConstant.IPMSG_RECVMSG);
					tmpCom.setAdditional("" + com.getPacketNo());
					tmpCom.setIp(com.getIp());
					UtilityNet.sendUdpPacket(tmpCom);
				} // end if

				System.out.println("idcomcn,mood:" + mood);

				int tmpPlace;
				switch (mood) {
				case IpmsgConstants.IPMSG_SENDMSG:
					receiveMessage(com);
					receiveFile(com);
					break;
				case 3:
				case 4:
					if ((tmpPlace = com.getAdditional().indexOf(0)) == -1) {
						GlobalVar.addUser(com.getIp(), com.getAdditional(), null, com.getSenderHost());
					} else {
						GlobalVar.addUser(com.getIp(), com.getAdditional().substring(0, tmpPlace),
								com.getAdditional().substring(tmpPlace + 1), com.getSenderHost());
					}

					this.fresh.refreshUsers();
					break;
				case 1:
					Command tmpCom = new Command(3);
					tmpCom.setAdditional(GlobalVar.USER_NAME + '\000' + "LanMsg");
					tmpCom.setIp(com.getIp());
					UtilityNet.sendUdpPacket(tmpCom);

					if ((tmpPlace = com.getAdditional().indexOf(0)) == -1) {
						GlobalVar.addUser(com.getIp(), com.getAdditional(), null, com.getSenderHost());
					} else {
						GlobalVar.addUser(com.getIp(), com.getAdditional().substring(0, tmpPlace),
								com.getAdditional().substring(tmpPlace + 1), com.getSenderHost());
					} // end if

					System.out.println(GlobalVar.getUserList());

					this.fresh.refreshUsers();
					break;
				case 2:
					GlobalVar.delUser(com.getIp());
					this.fresh.refreshUsers();
					break;
				case IpmsgConstants.IPMSG_RECVMSG:
					System.out.println("消息回复报文");
					break;
				case 0:
					System.out.println("空报文");
					break;
				case IpmsgConstants.IPMSG_RELEASEFILES:
					GlobalVar.delFileList(com.getAdditional().trim());
					break;
				default:
					System.out.println("其他报文");
				}
			}
		} catch (InterruptedException ex) {
		}
	}

	/**
	 * 接收消息
	 * 
	 * @param cmd
	 */
	private void receiveMessage(Command cmd) {
		if (cmd.getAdditionalHex().startsWith("00")) {
			return;
		} // end if
		int tmpPlace;
		tmpPlace = cmd.getAdditional().indexOf(0);
		if (tmpPlace > 0) {
			// TODO
			UtilityGui.newWindow(cmd.getIp(), cmd.getAdditional().substring(0, tmpPlace), cmd.getIp());
		}
	}

	/**
	 * 接收文件
	 * 
	 * @param cmd
	 */
	private void receiveFile(Command cmd) {
		if (!cmd.getAdditionalHex().startsWith("00")) {
			return;
		} // end if
		String strHex = cmd.getAdditionalHex().substring(2);
		byte[] buf = HexDataUtils.hexData2Bytes(strHex);

		String msg;
		try {
			msg = new String(buf, GlobalVar.CHARACTER_ENCODING);
		} catch (UnsupportedEncodingException ex) {
			return;
		} // end try

		FileLinkList fileList = FileLinkList.createFileLinkList(msg, cmd.getIp(), cmd.getPacketNo());

		if (fileList != null) {
			new GetRecFiles(fileList).setVisible(true);
		} // end if
	}
}
